package com.gqz.aircraftwar.mvp.model.aircraft

import android.graphics.PointF
import android.graphics.RectF
import com.gqz.aircraftwar.App
import com.gqz.aircraftwar.mvp.model.bomb.BlastManager
import com.gqz.aircraftwar.mvp.model.buff.Buff
import com.gqz.aircraftwar.mvp.model.bullet.Bullet
import com.gqz.aircraftwar.mvp.model.bullet.BulletManager
import com.gqz.aircraftwar.mvp.view.BasePath
import com.gqz.aircraftwar.util.*
import com.gqz.aircraftwar.util.CalcUtils.intersect
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * Descraption
 *
 * @author gqz
 * @data 2020/3/30
 */
class EnemyAircraft : Aircraft() {
    private val TAG: String = "EnemyAircraft-->"

    var path: BasePath? = null

    init {
        hp = 8f
        armor = 3
        speed = 8f
        attackSpeed = 0.8f
        atk_interval = (1000f / attackSpeed).toLong()
        dir = MyEnum.Dir.down
    }

    fun start() {
        try {
            GlobalScope.launch(BulletManager.ctx) {
                delay(1000)
                while (App.isRunning) {
//                    d(TAG, "running-->")
                    if (!free && inBounds()) {
                        BulletManager.instance.generateEnemyBullet(PointF(centerX(), pos.y), 0f)
                        delay(atk_interval)
                    } else {
                        delay(1000)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun set(
        type: MyEnum.EnemyType,
        appearance: Int,
        hp: Float,
        armor: Int,
        speed: Float,
        attackSpeed: Float
    ) {
        set(type, appearance, hp, armor, speed, attackSpeed, Buff.Null)
    }

    fun set(
        type: MyEnum.EnemyType,
        appearance: Int,
        hp: Float,
        armor: Int,
        speed: Float,
        attackSpeed: Float,
        buff: Buff
    ) {
        this.type = type
        this.appearance = BmpCache.loadBmp(appearance)
        this.hp = hp
        this.armor = armor
        this.speed = speed
        this.attackSpeed = attackSpeed
        if (buff != Buff.Null) {
            this.buffs.add(buff)
        }
    }

    //敌机移动，延路径移动
    fun moveByPath(offset: Float) {
        if (path?.moveEnd ?: true) {
            free = true
        } else {
            path?.move(this, offset)
        }
    }

    fun hit(player: Aircraft) {
        var rect = getRect()
        var isIntersect = rect.intersect(player.getRect())
        if (isIntersect) {
            v(TAG, "hit--> enemy hit player")
            player.hp -= hp
            if (player.hp <= 0) {
                player.dead()
            }
            dead()
        }
    }

}